package com.xunqi.springcloud.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.apache.commons.io.IOUtils;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@RestController
public class FileController {

    @Value("classpath:data/test.pdf")
    private Resource resource;

    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public ResponseEntity<byte[]> downFile(String e) throws IOException {

        ResponseEntity<byte[]> result = null;
        if(e != null){
            throw new RuntimeException("发生异常！");
        }
        try {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            InputStream inputStream = resource.getInputStream();
            int n = 0;
            while (-1 != (n = inputStream.read(buffer))) {
                output.write(buffer, 0, n);
            }
            HttpHeaders heads = new HttpHeaders();
//            heads.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=lr.xls");
            heads.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PDF_VALUE);

            result = new ResponseEntity<byte[]>(output.toByteArray(), heads, HttpStatus.OK);
        }finally {

        }
        return result;
    }


}
